from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from apps.students.models import Student
import re
import datetime


class StudentModelSerializer(ModelSerializer):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 将模型类的某个字段修改为必须字段或非必须字段
        self.fields['state'].required = True
        self.fields['sno'].required = False
        self.fields['staff'].required = False

    class Meta:
        model = Student
        fields = '__all__'

    def validate_telephone(self, value):
        """验证手机号"""
        if isinstance(value, str) and value != '' and (not re.match(r'^1[3-9]\d{9}$', value)):
            raise serializers.ValidationError('手机号格式错误!')
        return value

    def validate_age(self, value):
        """验证年龄"""
        if isinstance(value, int) and value < 0 or value > 300:
            raise serializers.ValidationError('输入年龄超过人类极限!')
        return value

    def create(self, validated_data):
        request = self.context.get('request')

        validated_data['sno'] = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3]
        validated_data['staff_id'] = request.user.id
        return super().create(validated_data)
